/**
 * axios 封装
 * @author maybe
 */
import axios from "axios";
import store from '@/store'
import { Toast,Dialog,Notify} from "vant";
import { getToken, getUserInfo } from "@/utils/auth";
import router from "@/router";
import configEnv from '_conf'
import { sortObj } from '@/utils/index'
import md5 from 'md5'// md5
/**
 * 请求失败后的错误统一处理
 * @param {number} code 请求失败的状态码
 */
const handleError = (res) => {
  switch (res.code) {
    case 100:
      // do something ...
      // 这里要清除一些全局的loading哦，例如 vant: Toast.clear()
      Dialog.alert({
        title: '友情提示',
        message: res.message,
      }).then(() => {
        let loginData=getUserInfo()
         console.log(loginData)
        if(loginData.type==3) {
          router.push("/loginDL");
        }else{
          router.push("/Login");
        }
        store.dispatch("user/logout")
        location.reload()
      });
      break;
    case 1:
      // do something ...
      // 这里要清除一些全局的loading哦，例如 vant: Toast.clear()
      Dialog.alert({
        title: '友情提示',
        message: res.message,
      }).then(() => {
        router.push("/course_buy");
      });
      break;
    default:
      Notify({ type: 'danger', message: res.message||'接口错误，请求后台帮助' });
      break;
  }
};
// create an axios instance
const service = axios.create({
  // withCredentials: true, // send cookies when cross-domain requests
  baseURL: configEnv.baseApi+'/index', // .env中配置的api前缀
  timeout: 5000, // request timeout
});
/**
 * 请求拦截器
 * 每次请求前，如果存在token则在请求头中携带token
 */
service.interceptors.request.use(
  (config) => {
    // 获取token
    const token = getToken();
    // 设置 sign
    try {
      // 文件上传处理
      config.data.append('token',token)
      const newObj = {}
      config.data.forEach((value, key) => {
        if (key !== 'file_excel' && key !== 'file' && key !== 'file[]') {
          newObj[key] = value
        }
      })
      const sign = md5( sortObj(newObj) + '854351') // 生成sign
      config.data.append('sign', sign)
    } catch (err) {
      config.data = {
        token: token||'',
        ...config.data
      }
      const sign = md5(sortObj(config.data)+ '854351') // 生成sign
      config.data = {
        sign,
        ...config.data
      }
    }
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error, "err");
    return Promise.reject(error);
  }
);
/**
 * 响应格式
 * { code => 状态码, msg => '响应信息', data => 数据 }
 */
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.code !== 200) {
      // 处理自定义错误
      handleError(res);
      return Promise.reject(new Error(res.message || "响应未知错误"));
    } else {
      // success
      return Promise.resolve(res);
    }
  },
  (error) => {
    console.error("response error:" + error); // for debug
    Toast.fail({
      message: error.message,
      duration: 1.5 * 1000,
    });
    return Promise.reject(error);
  }
);

export default service;
